package com.sjhh.print;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableNativeArray;
import com.gprinter.aidl.GpService;

import java.util.Set;

/**
 * Created by chensong on 2018/5/28.
 */

public class IntentModule extends ReactContextBaseJavaModule {

    private BluetoothAdapter mBtAdapter;
//    private PrinterServiceConnection conn;
    private GpService mGpService;
    private BluetoothDevice mDevice;

    public IntentModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "IntentModule";
    }

    /* 是否支持蓝牙 */
    @ReactMethod
    public void isSupport(Callback callback) {
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            callback.invoke(false);
            return;
        }
        callback.invoke(true);
    }

    /* 开启蓝牙  */
    @ReactMethod
    public void enableBluetooth(Callback callback) {
        // 打开蓝牙
        if (!mBtAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            // 设置蓝牙可见性，最多300秒
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            getCurrentActivity().startActivityForResult(intent, 0);

//            Toast.makeText(getCurrentActivity(), "蓝牙已开启", Toast.LENGTH_LONG);
        }
        // 获取已配对设备
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> devices = adapter.getBondedDevices();
        WritableNativeArray list = new WritableNativeArray();
        for (int i = 0; i < devices.size(); i++) {
            BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
            list.pushString(device.getName());
        }
        callback.invoke(list);
    }

    /* 跳转至原生界面 */
    @ReactMethod
    public void startActivityFromJS(String name, String params){
        try{
            Activity currentActivity = getCurrentActivity();
            if(null != currentActivity){
                Class toActivity = Class.forName(name);
                Intent intent = new Intent(currentActivity, toActivity);
                intent.putExtra("params", params);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                currentActivity.startActivity(intent);
            }
        }catch(Exception e){
            throw new JSApplicationIllegalArgumentException(
                    "不能打开Activity : "+e.getMessage());
        }
    }

}
